package com.csdj.t309springboot.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csdj.t309springboot.common.CacheConstant;
import com.csdj.t309springboot.entity.User;
import com.csdj.t309springboot.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.t309springboot.utils.EncryptUtil;
import com.csdj.t309springboot.utils.RandomUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author cloud
 * @since 2021-12-30
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private RedisService redisService;

    @Override
    public User login(String username, String password) {
        String dePass = EncryptUtil.getMd5(password);
        if(StringUtils.hasText(dePass)){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getUsername,username).eq(User::getPassword,dePass);
            User user = getOne(queryWrapper);
            if(user != null){
                setToken(user);
                redisService.setString(CacheConstant.TOKEN_PREFIX+user.getId(),user.getToken(),1800);
                return user;
            }
        }
        return null;
    }

    @Override
    public void addUsersByRandom(int num) {
        String pass = EncryptUtil.getMd5("123456");
        List<User> list = new ArrayList<>();
        IntStream.range(0,num).forEach(i ->{
            User user = new User();
            user.setUsername(RandomUtil.genChars(8));
            user.setPassword(pass);
            user.setStatus(1);
            user.setCreateTm(LocalDateTime.now());
            user.setRoleId(2);
            user.setTopId(0);
            user.setLastLoginTm(LocalDateTime.now());
//            save(user);
            list.add(user);
        });
        saveBatch(list);
    }


    @Override
    public boolean update(User user){
        if(StringUtils.hasText(user.getPassword())){
            user.setPassword(EncryptUtil.getMd5(user.getPassword()));
        }
        return updateById(user);
    }


    private void setToken(User user){
        if(user != null){
            user.setToken(RandomUtil.genToken());
        }
    }
}
